package xml;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlDemo1 {

	public static void main(String[] args) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(new File("D:\\Users\\pfzhang.CN1\\Desktop\\����.xml"));
		// System.out.println(java.net.URLEncoder.encode("D:\\Users\\pfzhang.CN1\\Desktop\\����.xml","UTF-8"));

		// <wordbook>
		// <item id="haha">
		// <word>feature</word>
		// </item>
		// <item id= "hehe">
		// <word>terminate</word>
		// <trans>dsfadsf</trans>
		// </item>
		// </wordbook>

		Element root = document.getDocumentElement();
		NodeList nodeList = root.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node instanceof Element) {

				System.out.println(node.getNodeName() + ":" + ((Element) node).getAttribute("id"));// ��һ���ӽڵ�item

				NamedNodeMap map = node.getAttributes();// �ڵ����������
				for (int j = 0; j < map.getLength(); j++) {
					System.out.println(map.item(j).getNodeName() + "��" + map.item(j).getNodeValue());
				}
			}
		}

		List<String> list = new ArrayList<String>();
		NodeList words = document.getElementsByTagName("word");// ��ȡ����word�ӽڵ�
		System.out.println(words.getLength());
		for (int i = 0; i < words.getLength(); i++) {
			Node node = words.item(i);
			System.out.println(node.getFirstChild().getNodeValue());// �ڵ�����
			list.add(node.getFirstChild().getNodeValue());

		}

		// ��ĸ����˳��
		list.sort(new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});

		StringBuilder sb = new StringBuilder();
		for (int j = 0; j < list.size(); j++) {
			if (!list.get(j).contains(" ") && list.contains(list.get(j))) {
				sb.append(list.get(j) + ((j + 1) < words.getLength() ? "," : ""));
			}
		}

		ByteArrayInputStream byteStream = new ByteArrayInputStream(sb.toString().getBytes());
		try (FileOutputStream fos = new FileOutputStream("D:\\Users\\pfzhang.CN1\\Desktop\\����ת����.txt")) {
			byte[] data = new byte[1024];
			int length = 0;
			while ((length = byteStream.read(data, 0, data.length)) != -1) {
				fos.write(data, 0, length);
				fos.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
